import RefereEdit from '@/assets/image/refere-edit.png';
import {
  mainPointTitle,
  pullPointAndTitle,
  updateMainPoint,
} from '@/services/ant-design-pro/highClassWrite';
import { LoadingOutlined } from '@ant-design/icons';
import { connect } from '@umijs/max';
import { Button, Divider, Input, message, Modal, Spin } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import './index.less';
const ArticleOutline: React.FC<any> = forwardRef((props, ref) => {
  const [edit, setEdit] = useState<boolean>(false);
  const [disabled, setDisabled] = useState<boolean>(true);
  const [outlineEdit, setOutlineEdit] = useState<boolean>(false);
  const [outlineDisabled, setOutlineDisabled] = useState<boolean>(true);
  const [theme, setTheme] = useState<string>('');
  const [originTheme, setOriginTheme] = useState<string>('');
  const [outline, setOutline] = useState<string>('');
  const [originOutline, setOriginOutline] = useState<string>('');
  const [updateThemeOpen, setUpdateThemeOpen] = useState<boolean>(false);
  const [updating, setUpdating] = useState<boolean>(false);
  const { TextArea } = Input;

  //预留触发更新数据
  const updateData = async () => {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    let res = await getPointAndTitle();
    return res;
  };

  //预留触发的方法
  useImperativeHandle(ref, () => ({
    updateData,
  }));

  const getPointAndTitle = async () => {
    if (!props.highClassWrite.writing_session_id) return;
    const params: any = {
      write_session_id: props.highClassWrite.writing_session_id,
    };
    // 拉取大纲、主题
    const res = await pullPointAndTitle(params);
    if (res.code === 0) {
      const { title, main_point } = res.data;
      setTheme(title);
      setOriginTheme(title);
      setOutline(main_point);
      setOriginOutline(main_point);
    } else {
      message.error(res.msg);
    }
    return res;
  };

  const editAglin = (type: string) => {
    if (type === 'theme') {
      if (updating) return;
      setEdit(true);
      setDisabled(false);
    } else {
      setOutlineEdit(true);
      setOutlineDisabled(false);
    }
  };

  const cancelEdit = (type: string) => {
    if (type === 'theme') {
      setEdit(false);
      setDisabled(true);
      setTheme(originTheme);
    } else {
      setOutlineEdit(false);
      setOutlineDisabled(true);
      setOutline(originOutline);
    }
  };

  const updateTheme = async () => {
    if (!theme) {
      message.error('请输入文章主题');
      return;
    }
    setUpdating(true);
    // 更新主题
    const params: any = {
      write_session_id: props.highClassWrite.writing_session_id,
      title: theme,
    };
    const res: any = await mainPointTitle(params);
    if (res.code === 0) {
      message.success('文章主题已更新');
      const { title, main_point } = res.data;
      setTheme(title);
      setOriginTheme(title);
      setOutline(main_point);
      setOriginOutline(main_point);
    } else {
      message.error(res.msg);
    }

    setUpdating(false);
  };

  const saveEdit = async (type: string) => {
    if (type === 'theme') {
      setEdit(false);
      setDisabled(true);
      if (!theme) {
        message.error('请输入文章主题');
        return;
      }
      if (theme === originTheme) return;
      setUpdateThemeOpen(true);
    } else {
      setOutlineEdit(false);
      setOutlineDisabled(true);
      // 更新大纲
      if (!outline) {
        message.error('请输入文章大纲');
        return;
      }
      // 更新大纲
      const params: any = {
        write_session_id: props.highClassWrite.writing_session_id,
        main_point: outline,
      };
      const res: any = await updateMainPoint(params);
      if (res.code === 0) {
        const { main_point } = res.data;
        setOriginOutline(main_point);
        message.success('文章大纲已更新');
      } else {
        message.error(res.msg);
      }
    }
  };

  const handleThemeEdit = (e: any) => {
    const newTheme = e.target.value || '';
    setTheme(newTheme);
  };

  const handleOutlineEdit = (e: any) => {
    const newOutline = e.target.value || '';
    setOutline(newOutline);
  };

  const onConfirm = async () => {
    setUpdateThemeOpen(false);
    updateTheme();
  };

  const editEl = () => {
    if (updating) {
      const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
      return <Spin indicator={antIcon} />;
    } else {
      return <img src={RefereEdit} alt="" width={39} height={39} />;
    }
  };

  useEffect(() => {
    setTimeout(() => {
      getPointAndTitle();
    }, 10);
  }, [props.highClassWrite.writing_session_id]);

  return (
    <div className="articleOutlineWrap">
      <div className="reference__outline">
        <div className="reference__outline-title">
          <span>文章主题</span>
          <div className="reference__outline-edit">
            {/* 编辑 */}
            {!edit ? (
              <div
                onClick={() => editAglin('theme')}
                style={{ color: '#3E4352', cursor: 'pointer' }}
              >
                {editEl()}
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'row', color: '#979797' }}>
                <div
                  onClick={() => cancelEdit('theme')}
                  style={{ color: '#3E4352', opacity: '0.7', cursor: 'pointer', padding: '0 10px' }}
                >
                  取消
                </div>{' '}
                |
                <div
                  onClick={() => saveEdit('theme')}
                  style={{ color: '#397BFF', cursor: 'pointer', paddingLeft: '10px' }}
                >
                  确定
                </div>
              </div>
            )}
          </div>
        </div>
        <div className="reference__outline-content">
          <TextArea
            placeholder="暂无主题"
            bordered={!disabled}
            disabled={disabled}
            autoSize={{ maxRows: 4, minRows: 1 }}
            value={theme}
            onChange={(e) => {
              handleThemeEdit(e);
            }}
          ></TextArea>
          <Divider dashed />
        </div>
      </div>
      <div className="reference__outline">
        <div className="reference__outline-title">
          <span>文章大纲</span>
          <div className="reference__outline-edit">
            {!outlineEdit ? (
              <div
                onClick={() => editAglin('outline')}
                style={{ color: '#3E4352', cursor: 'pointer' }}
              >
                <img
                  src={RefereEdit}
                  alt=""
                  width={39}
                  height={39}
                  style={{ marginRight: '6px' }}
                />
                {/* 编辑 */}
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'row', color: '#979797' }}>
                <div
                  onClick={() => cancelEdit('outline')}
                  style={{ color: '#3E4352', opacity: '0.7', cursor: 'pointer', padding: '0 10px' }}
                >
                  取消
                </div>{' '}
                |
                <div
                  onClick={() => saveEdit('outline')}
                  style={{ color: '#397BFF', cursor: 'pointer', paddingLeft: '10px' }}
                >
                  确定
                </div>
              </div>
            )}
          </div>
        </div>
        <div className="reference__outline-content">
          <TextArea
            placeholder="暂无大纲"
            bordered={!outlineDisabled}
            disabled={outlineDisabled}
            value={outline}
            onChange={(e) => {
              handleOutlineEdit(e);
            }}
            className="outline-h"
          ></TextArea>
        </div>
      </div>
      <Modal
        title="注意"
        open={updateThemeOpen}
        onOk={(e) => {
          e.stopPropagation();
          onConfirm();
        }}
        onCancel={(e) => {
          e.stopPropagation();
          setTheme(originTheme);
          setUpdateThemeOpen(false);
        }}
        width={350}
        okText="确定"
        cancelText="取消"
        footer={[
          <Button
            key="back"
            onClick={(e) => {
              e.stopPropagation();
              setTheme(originTheme);
              setUpdateThemeOpen(false);
            }}
          >
            取消
          </Button>,
          <Button
            type="primary"
            danger
            onClick={(e) => {
              e.stopPropagation();
              onConfirm();
            }}
            key="confirm"
          >
            确定
          </Button>,
        ]}
      >
        <p>文章主题修改后，文章大纲将会重新生成，是否确定要修改？</p>
      </Modal>
    </div>
  );
});

export default connect(({ highClassWrite }) => ({ highClassWrite }), null, null, {
  forwardRef: true,
})(ArticleOutline);
